package Problem;

public class Number2 implements Runnable {
    final int  SUCCESS =8;
    int realNumber,guessNumber,min =0,max =100,message = -1;
    boolean pleaseGuess = false ,isGivenNumber = false;
    Thread giveNumberThread,guessNumberThread;
    Number2(){
        giveNumberThread = new Thread(this); //创建giveNumberThread，当前Number类的实例是giveNumberThread的目标对象
        guessNumberThread = new Thread(this); //创建guessNumberThread，当前Number类的实例是giveNumberThread的目标对象
    }

    @Override
    public void run() {
        for (int count=1; true; count++) {
            setMessage(count);
            if(message ==SUCCESS) {
                return;
            }

        }

    }

    public synchronized void setMessage(int count) {
        if(Thread.currentThread()==giveNumberThread&&isGivenNumber == false) {
            realNumber = (int)(Math.random()*100)+1;
            System.out.println("随机给你一个1至100之间的数，猜猜是多少？");
            isGivenNumber = true;
            pleaseGuess =true;
        }
        if(Thread.currentThread()==giveNumberThread) {
            while(pleaseGuess==true) {  //如果还没猜数字
                try {
                    wait();

                } catch (InterruptedException e) {}
            }
            if(realNumber>guessNumber) {
                min =guessNumber+1;
                System.out.println("你猜小了");
            }
            else if(realNumber<guessNumber) {
                max = guessNumber -1;
                System.out.println("你猜大了");
            }
            else{
                message=SUCCESS;
                System.out.println("恭喜，你猜对了");
                return;
            }
            pleaseGuess =true;	  //已经判断完，需重新猜
        }
        if(Thread.currentThread()==guessNumberThread&&isGivenNumber == true) {
            while(pleaseGuess==false)   //如果已经猜了数字
                try {
                    wait();
                }
                catch (InterruptedException e) {}

            guessNumber = (min+max)/2;

            System.out.println("我第" + count + "次猜这个数是" + guessNumber);

            pleaseGuess=false;
        }
        notifyAll();
    }
}
//在记事本、sublime3或者eclipse中新建TwoThGuessNumber.java，输入以下代码：


